<?php

namespace app\controller\api;

use app\controller\api\Base;
use app\model\ClearanceModel;
use app\model\ConfigModel;
use app\model\GoodsModel;
use app\model\ReleaseScopeModel;
use app\model\SizeModel;
use app\model\VehicleModel;
use app\Request;
use app\validate\Check;
use think\App;
use think\facade\Db;
use app\model\DeliveryModel;
use app\model\AddressModel;

class Index extends Base
{
    public $token;
    public $version;
    public $lang;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->token = $this->request->header('xzdToken');
        $this->version = $this->request->header('version');
        $this->lang = $this->request->header('lang');
    }


    /**
     * @param Request $request
     * @param SizeModel $sizeModel
     * @notes 发货载具尺寸
     * @author: dongdong
     * @date: 2025/1/7 15:40
     */
    public function delivery_size(Request $request, SizeModel $sizeModel)
    {
        $param = $request->param();
        $data = $sizeModel::lists($param);
        $this->api_result(200, '请求成功', ['data' => $data]);
    }


    /**
     * @param Request $request
     * @param VehicleModel $vehicleModel
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @notes 发货载具车型 箱型
     * @author: dongdong
     * @date: 2025/1/7 15:43
     */
    public function delivery_vehicle(Request $request, VehicleModel $vehicleModel)
    {
        $param = $request->param();
        $data = $vehicleModel::lists($param);
        $this->api_result(200, '请求成功', ['data' => $data]);
    }

    /**
     * @param Request $request
     * @param VehicleModel $vehicleModel
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @notes  发货载具和尺寸 互选
     * @author: dongdong
     * @date: 2025/1/7 16:06
     */
    public function size_vehicle(Request $request, VehicleModel $vehicleModel)
    {
        $param = $request->param();
        $data = $vehicleModel::size_vehicle($param);
        $this->api_result(200, '请求成功', ['data' => $data]);
    }


    /**
     * @return array|\think\Collection|\think\db\BaseQuery[]
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @notes GLUZ货运期间服务相关协议
     * @author: dongdong
     * @date: 2025/1/2 10:05
     */
    public function delivery_content()
    {
        try {
            $data = Db::connect('fast_mysql')->table("fa_content")->where("id", "in", "25,26,27,28")->field("id,type,title,content")->select();
            $this->api_result(200, '请求成功', ['data' => $data]);
        } catch (\Exception $e) {
            $this->api_result(400, '请求失败', ['data' => []]);
        }
    }


    /**
     * @param Request $request
     * @param ConfigModel $configModel
     * @notes 铁路 车皮列表
     * @author: dongdong
     * @date: 2025/1/8 10:23
     */
    public function railway_wagon(Request $request, ConfigModel $configModel)
    {
        $param = $request->param();
        $data = $configModel->railway_wagon($param['user_id'] ?? '',$param['type']??0);
        $this->api_result(200, '请求成功', ['data' => $data]);
    }


    /**
     * @param Request $request
     * @param ConfigModel $configModel
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @notes 包装方式
     * @author: dongdong
     * @date: 2025/1/1 11:43
     */
    public function package(Request $request, ConfigModel $configModel)
    {
        $param = $request->param();
        $data = $configModel->package($param['user_id'] ?? '');
        $this->api_result(200, '请求成功', ['data' => $data]);
    }

    /**
     * @param Request $request
     * @param ConfigModel $configModel
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @notes 卸货方式
     * @author: dongdong
     * @date: 2025/1/1 14:17
     */
    public function unload(Request $request, ConfigModel $configModel)
    {
        $param = $request->param();
        $data = $configModel->unload($param['user_id'] ?? '');
        $this->api_result(200, '请求成功', ['data' => $data]);
    }


    /**
     * @param Request $request
     * @param Check $check
     * @param GoodsModel $goodsModel
     * @notes 货物添加
     * @author: dongdong
     * @date: 2025/1/1 11:24
     */
    public function goods(Request $request, Check $check, GoodsModel $goodsModel)
    {
        try {
            $param = $request->param();
            $param['token'] = $this->token;
            $param['version'] = $this->version;
            $param['lang'] = $this->lang;
            $result = $check->scene('goods')->check($param);
            if (!$result) {
                $this->api_result(400, $check->getError(), []);
            } else {
                $data = $goodsModel->add($param);
                if ($data) {
                    $this->api_result(200, '请求成功', ['data' => $data]);
                } else {
                    $this->api_result(400, '请求失败', []);
                }
            }
        } catch (\Exception $e) {
            $this->api_result(400, '请求失败!', _d($e));
        }
    }


    /**
     * @param Request $request
     * @param Check $check
     * @param AddressModel $addressModel
     * @notes 选择地点
     * @author: dongdong
     * @date: 2025/1/1 10:29
     */
    public function select_address(Request $request, Check $check, AddressModel $addressModel)
    {
        try {
            $param = $request->param();
            $param['token'] = $this->token;
            $param['version'] = $this->version;
            $param['lang'] = $this->lang;
            $result = $check->scene('select_address')->check($param);
            if (!$result) {
                $this->api_result(400, $check->getError(), []);
            } else {
                $data = $addressModel->add($param);
                if ($data) {
                    $this->api_result(200, '请求成功', ['data' => $data]);
                } else {
                    $this->api_result(400, '请求失败', []);
                }
            }
        } catch (\Exception $e) {
            $this->api_result(400, '请求失败!', _d($e));
        }
    }


    /**
     * @return \think\response\Json
     * @notes 普通发货
     * @author: dongdong
     * @date: 2024/12/23 14:33
     */
    public function delivery(Request $request, Check $check, DeliveryModel $deliveryModel)
    {
        try {
            $param = $request->param();
            $param['token'] = $this->token;
            $param['version'] = $this->version;
            $param['lang'] = $this->lang;
            $result = $check->scene('delivery')->check($param);
            if (!$result) {
                $this->api_result(400, $check->getError(), []);
            } else {
                $data = $deliveryModel->add($param);
                if ($data) {
                    $this->api_result(200, '请求成功', ['data' => $data, 'notice_count' => 0]);
                } else {
                    $this->api_result(400, '请求失败', []);
                }
            }
        } catch (\Exception $e) {
            $this->api_result(400, '请求失败!', _d($e));
        }
    }


    /**
     * @param Request $request
     * @param DeliveryModel $deliveryModel
     * @notes 呈现路线
     * @author: dongdong
     * @date: 2025/1/3 13:51
     */
    public function route_present(Request $request, DeliveryModel $deliveryModel)
    {
        try {
            $param = $request->param();
            $order_sn = 'route_' . date('YmdHis') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
            $route = $deliveryModel->delivery_route($param, $order_sn,1);
            if ($route) {
                $data = $deliveryModel->route_list($order_sn);
                $this->api_result(200, '请求成功', ['data' => $data]);
            } else {
                $this->api_result(400, '请求失败', ['data' => []]);
            }
        } catch (\Exception $e) {
            $this->api_result(400, '请求失败!', _d($e));
        }
    }


    /**
     * @param Request $request
     * @param ReleaseScopeModel $releaseScopeModel
     * @notes 信息发布范围筛选
     * @author: dongdong
     * @date: 2025/1/7 13:39
     */
    public function release_scope_search(Request $request, ReleaseScopeModel $releaseScopeModel, Check $check)
    {
        try {
            $param = $request->param();
            $param['token'] = $this->token;
            $param['version'] = $this->version;
            $param['lang'] = $this->lang;
            $result = $check->scene('check')->check($param);
            if (!$result) {
                $this->api_result(400, $check->getError(), []);
            } else {
                $data = $releaseScopeModel->search_list($param);
                $this->api_result(200, '请求成功', ['data' => $data]);
            }
        } catch (\Exception $e) {
            $this->api_result(400, '请求失败!', _d($e));
        }
    }


    /**
     * @param Request $request
     * @param DeliveryModel $deliveryModel
     * @param Check $check
     * @notes 货源信息
     * @author: dongdong
     * @date: 2025/1/13 17:51
     */
    public function delivery_select(Request $request, DeliveryModel $deliveryModel, Check $check)
    {
        try {
            $param = $request->param();
            $param['token'] = $this->token;
            $param['version'] = $this->version;
            $param['lang'] = $this->lang;
            $result = $check->scene('check')->check($param);
            if (!$result) {
                $this->api_result(400, $check->getError(), []);
            } else {
                $data = $deliveryModel->delivery_select($param);
                $this->api_result(200, '请求成功', ['data' => $data]);
            }
        } catch (\Exception $e) {
            $this->api_result(400, '请求失败!', _d($e));
        }
    }

    /**
     * @param Request $request
     * @param DeliveryModel $deliveryModel
     * @param Check $check
     * @notes 车源信息
     * @author: dongdong
     * @date: 2025/1/13 17:51
     */
    public function car_source(Request $request, DeliveryModel $deliveryModel, Check $check)
    {
        try {
            $param = $request->param();
            $param['token'] = $this->token;
            $param['version'] = $this->version;
            $param['lang'] = $this->lang;
            $result = $check->scene('check')->check($param);
            if (!$result) {
                $this->api_result(400, $check->getError(), []);
            } else {
                $data = $deliveryModel->car_source($param);
                $this->api_result(200, '请求成功', ['data' => $data]);
            }
        } catch (\Exception $e) {
            $this->api_result(400, '请求失败!', _d($e));
        }
    }


    /**
     * @param VehicleModel $vehicleModel
     * @notes 车源类型筛选
     * @author: dongdong
     * @date: 2025/1/15 16:20
     */
    public function car_brand_search(VehicleModel $vehicleModel)
    {
        try {
            $transport_way = input('barIndex')??'';
            $where = "";
            if($transport_way){
                $where = "transport_way='$transport_way'";
            }
            $list = $vehicleModel->field("id,title,title_ru,transport_way")->where("status=1 and is_deleted=0")->where($where)->select();
            foreach ($list as $k => &$v) {
                $v['val'] = $v['transport_way'] . ',' . $v['id'];
                if ($v['transport_way'] == 2) {
                    $v['text'] = '汽运';
                    $v['text_ru'] = 'Автотранспорт';
                }
                if ($v['transport_way'] == 3) {
                    $v['text'] = '空运';
                    $v['text_ru'] = 'Воздушные перевозки';
                }
                if ($v['transport_way'] == 4) {
                    $v['text'] = '海运';
                    $v['text_ru'] = 'Морские перевозки';
                }
                if ($v['transport_way'] == 5) {
                    $v['text'] = '铁路';
                    $v['text_ru'] = 'Поезд';
                }

                $v['val_name'] = $v['text'].'-'.$v['title'];
                $v['val_name_ru'] = $v['text_ru'].'-'.$v['title_ru'];


            }
            $this->api_result(200, '请求成功', ['data' => $list]);
        } catch (\Exception $e) {
            $this->api_result(200, '请求成功', ['data' => []]);
        }
    }


    /**
     * @param Request $request
     * @param ClearanceModel $clearanceModel
     * @param Check $check
     * @notes 请求通关服务
     * @author: dongdong
     * @date: 2025/1/15 16:22
     */
    public function request_clearance(Request $request, ClearanceModel $clearanceModel, Check $check)
    {
        try {
            $param = $request->param();
            $param['token'] = $this->token;
            $param['version'] = $this->version;
            $param['lang'] = $this->lang;
            $result = $check->scene('request_clearance')->check($param);
            if (!$result) {
                $this->api_result(400, $check->getError(), []);
            } else {
                $data = $clearanceModel->request_clearance($param);
                $this->api_result(200, '请求成功', ['data' => $data]);
            }
        } catch (\Exception $e) {
            $this->api_result(400, '请求失败!', _d($e));
        }
    }


    /**
     * @param Request $request
     * @param ClearanceModel $clearanceModel
     * @param Check $check
     * @notes 历史记录
     * @author: dongdong
     * @date: 2025/2/19 11:37
     */
    public function history_list(Request $request, ClearanceModel $clearanceModel, Check $check)
    {
        try {
            $param = $request->param();
            $param['token'] = $this->token;
            $param['version'] = $this->version;
            $param['lang'] = $this->lang;
            $result = $check->scene('history_list')->check($param);
            if (!$result) {
                $this->api_result(400, $check->getError(), []);
            } else {
                $data = $clearanceModel->history_list($param);
                $this->api_result(200, '请求成功', ['data' => $data]);
            }
        } catch (\Exception $e) {
            $this->api_result(400, '请求失败!', _d($e));
        }
    }


    /**
     * @param Request $request
     * @param Check $check
     * @param ClearanceModel $clearanceModel
     * @notes 插入历史记录
     * @author: dongdong
     * @date: 2025/2/19 15:49
     */
    public function insert_history(Request $request, Check $check,ClearanceModel $clearanceModel){
        try {
            $param = $request->param();
            $param['token'] = $this->token;
            $param['version'] = $this->version;
            $param['lang'] = $this->lang;
            $result = $check->scene('history_list')->check($param);
            if (!$result) {
                $this->api_result(400, $check->getError(), []);
            } else {
                $data = $clearanceModel->insert_history($param);
                $this->api_result(200, '请求成功', ['data' => $data]);
            }
        } catch (\Exception $e) {
            $this->api_result(400, '请求失败!', _d($e));
        }
    }




    /**
     * @param DeliveryModel $deliveryModel
     * @param Request $request
     * @notes 关联订单
     * @author: dongdong
     * @date: 2025/1/22 11:10
     */
    public function related_order(DeliveryModel $deliveryModel, Request $request)
    {
        $param = $request->param();
        $page = $param['page'] ?? 1;
        $user_id = $param['user_id'] ?? '';
        $limit = $param['limit'] ?? 100;
        $goods_type = $param['goods_type'] ?? '';

        try {
            $where = "1";
            if ($goods_type == '') {
                $where .= "";
            } elseif ($goods_type == 0) {
                $where .= " and d.goods_type=0";
            } elseif ($goods_type == 1) {
                $where .= " and d.goods_type=1";
            }


            $page = ($page - 1) * $limit;
            if($user_id){
                $list = Db::query("select d.* from store_delivery d left join store_delivery_attach a on d.id=a.delivery_id where $where and d.status=2  and find_in_set($user_id,a.cooperate_user_id) order by d.id desc limit $page,$limit");
                $data = $deliveryModel->record_handle($list,$user_id);
                $this->api_result(200, '请求成功', ['data' => $data]);
            }else{
                $this->api_result(400, '请求失败!', []);
            }

        }catch (\Exception $e){
            $this->api_result(400, '请求失败!', []);
        }

    }


    /**
     * @param DeliveryModel $deliveryModel
     * @param Request $request
     * @notes 发货详情
     * @author: dongdong
     * @date: 2025/1/22 11:17
     */
    public function delivery_find(DeliveryModel $deliveryModel, Request $request)
    {
        $param = $request->param();
        $id = $param['delivery_id'] ?? '';
        $list = Db::query("select d.* from store_delivery d left join store_delivery_attach a on d.id=a.delivery_id where d.id = '$id'");
        Db::query("update store_delivery_attach set lookat_number=lookat_number+1 where delivery_id=$id");
        $data = $deliveryModel->record_handle($list,$param['user_id']??'');
        if ($data) {
            $this->api_result(200, '请求成功', ['data' => $data[0]]);
        } else {
            $this->api_result(400, '请求失败', ['data' => '']);
        }
    }


    /**
     * @param DeliveryModel $deliveryModel
     * @param Request $request
     * @throws \think\db\exception\DbException
     * @notes 确认收货
     * @author: dongdong
     * @date: 2025/3/4 9:51
     */
    public function delivery_take(DeliveryModel $deliveryModel, Request $request){
        $param = $request->param();
        $id = $param['delivery_id'] ?? '';
        $find = Db::table("store_delivery")->where(['id'=>$id])->find();
        if($find){
            if($find['status']==3){
                Db::table("store_delivery")->where(['id'=>$id])->update(['status'=>4]);
                Db::table("store_delivery_attach")->where(['delivery_id'=>$id])->update(['take_at'=>date('Y-m-d H:i:s')]);

                $car = Db::table("store_car")->where(['order_id'=>$id])->find();
                if($car){
                    Db::table("store_car")->where(['id'=>$car['id']])->update(['order_id'=>0,'status'=>1,'send_jb_time'=>0]);
                }

                $this->api_result(200, '请求成功', ['data' => []]);
            }else {
                $this->api_result(400, '此状态不能确定收货', ['data' => '']);
            }
        }else {
            $this->api_result(400, '未找到记录', ['data' => '']);
        }
    }


    /**
     * @param Request $request
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @notes 请求记录
     * @author: dongdong
     * @date: 2025/3/4 10:12
     */
    public function request_record(Request $request){
        $param = $request->param();
        $user_id = $param['user_id'];
        $data = Db::table("store_request_list")->where(['user_id'=>$user_id])->where("type=1")->order("id desc")->select();
        $arr = [];
        foreach ($data as $k => &$v) {
            $v['mine'] = Db::connect("fast_mysql")->table("fa_user")->where(['id' => $v['user_id']])->field("id,username,username_ru,mobile,level,avatar")->find();
            $v['request_user'] = Db::connect("fast_mysql")->table("fa_user")->where(['id' => $v['service_user_id']])->field("id,username,username_ru,mobile,level,avatar")->find();
            if($v['request_user']){
                $v['request_user']['car'] = Db::table("store_car")->where(['id'=>$v['car_id']])->find();
            }
            $v['remark'] = Db::table("store_remark")->where(["id"=>$v['content_id']])->find();
            if($v['image']){
                $v['images'] = explode(',',$v['image']);
            }else{
                $v['images'] = [];
            }
            array_push($arr, $v);
        }
        if($arr){
            $this->api_result(200, '请求成功', ['data' => $arr, 'count' => count($arr)]);
        }else{
            $this->api_result(200, '请求成功', ['data' => [], 'count' => 0]);
        }
    }


    /**
     * @notes 流程模板
     * @author: dongdong
     * @date: 2025/3/4 13:41
     */
    public function process_template(){
        $arr = ['请先确认 收到货物是否正确 数量是否正确 包装是否完好并及时 上传图片视频','请先确认 请上传货物仓储情况 位置 和图片及视频','请填写货物 通关情况 和通关状态','请最好每日填写货车运输位置 和货物安全情况','最后请每一个员工将完成状态上传到运综系统中'];
        $this->api_result(200, '请求成功', ['data' => $arr, 'count' => 1]);
    }


}